<template>
  <div class="main">
    <!-- 头部输入框 -->
    <el-form :model="queryParams" size="small" :inline="true">
      <el-form-item label="资讯标题">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入内容"
          style="width: 200px"
        ></el-input>
      </el-form-item>

      <el-form-item label="作者">
        <el-input
          v-model="queryParams.editor"
          placeholder="请输入内容"
          style="width: 200px"
        ></el-input>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="handleRefresh"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 功能按钮 -->
    <el-row>
      <el-button
        type="success"
        icon="el-icon-plus"
        size="mini"
        @click="handleAdd"
        >新增</el-button
      >
      <el-button
        type="info"
        icon="el-icon-delete"
        :disabled="multiple"
        size="mini"
        @click="handleDelete"
        >删除</el-button
      >
    </el-row>

    <!-- 表格 -->
    <el-table
      :data="tableData"
      style="width: 100%"
      :row-style="{ height: '180px' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="标题" width="180" align="center">
        <template slot-scope="scope">
          <el-tooltip
            class="item"
            effect="light"
            :content="scope.row.title"
            placement="top"
          >
            <div class="omit title">
              {{ scope.row.title }}
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="资讯图" width="100" align="center">
        <template slot-scope="scope">
          <img
            :src="url + scope.row.bucketName + '/' + scope.row.fileName"
            style="height: 100px"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="articleViews"
        label="访问量"
        width="60"
        align="center"
      >
      </el-table-column>
      <el-table-column prop="editor" label="作者" width="70" align="center">
      </el-table-column>
      <el-table-column prop="reviewer" label="审核人" width="70" align="center">
      </el-table-column>
      <el-table-column label="内容" align="center">
        <template slot-scope="scope">
          <div class="omit content" v-html="scope.row.content"></div>
        </template>
      </el-table-column>

      <el-table-column label="备注" width="200" align="center">
        <template slot-scope="scope">
          <div class="omit remark">
            {{ scope.row.remark }}
          </div>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="marketUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="80%"
      :before-close="handleClose"
    >
      <!-- 对话框主体部分 -->
      <el-form :model="form" ref="form" :rules="rules">
        <el-form-item
          label="资讯标题"
          prop="title"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.title" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="作者" prop="editor" :label-width="formLabelWidth">
          <el-input v-model="form.editor" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="内容" prop="content" :label-width="formLabelWidth">
          <!-- 富文本编辑器 -->
          <quill-editor
            v-model="form.content"
            ref="myQuillEditor"
            :options="editorOption"
            @blur="onEditorBlur($event)"
            @focus="onEditorFocus($event)"
            @change="onEditorChange($event)"
            @ready="onEditorReady($event)"
          >
          </quill-editor>
          <!-- 上传图片（隐藏） -->
          <el-upload
            v-show="false"
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :http-request="onUploadHandler"
            :before-upload="ImgBeforeAvatarUpload1"
          >
          </el-upload>
        </el-form-item>

        <el-form-item
          label="审核人"
          prop="reviewer"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.reviewer" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="资讯图片" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :http-request="upload"
            :before-upload="ImgBeforeAvatarUpload"
            :key="keyVal"
          >
            <img
              v-if="url + form.bucketName + '/' + form.fileName"
              :src="url + form.bucketName + '/' + form.fileName"
              style="width: 100px"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input v-model="form.remark" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getBranch,
  addBranch,
  updateBranch,
  delBranch,
} from "@/api/branchInformation/branch.js";
import global from "@/global/global.js";
import { addFile } from "@/api/uploadFile/file";

import { quillEditor } from "vue-quill-editor";

import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { Base64 } from "js-base64";

import Quill from "quill";
import ImageResize from "quill-image-resize-module"; // 引用
import { ImageDrop } from "quill-image-drop-module";
Quill.register("modules/imageDrop", ImageDrop);
Quill.register("modules/imageResize", ImageResize); // 注册
// toolbar标题
const titleConfig = [
  { Choice: ".ql-insertMetric", title: "跳转配置" },
  { Choice: ".ql-bold", title: "加粗" },
  { Choice: ".ql-italic", title: "斜体" },
  { Choice: ".ql-underline", title: "下划线" },
  { Choice: ".ql-header", title: "段落格式" },
  { Choice: ".ql-strike", title: "删除线" },
  { Choice: ".ql-blockquote", title: "块引用" },
  { Choice: ".ql-code", title: "插入代码" },
  { Choice: ".ql-code-block", title: "插入代码段" },
  { Choice: ".ql-font", title: "字体" },
  { Choice: ".ql-size", title: "字体大小" },
  { Choice: '.ql-list[value="ordered"]', title: "编号列表" },
  { Choice: '.ql-list[value="bullet"]', title: "项目列表" },
  { Choice: ".ql-direction", title: "文本方向" },
  { Choice: '.ql-header[value="1"]', title: "h1" },
  { Choice: '.ql-header[value="2"]', title: "h2" },
  { Choice: ".ql-align", title: "对齐方式" },
  { Choice: ".ql-color", title: "字体颜色" },
  { Choice: ".ql-background", title: "背景颜色" },
  { Choice: ".ql-image", title: "图像" },
  { Choice: ".ql-video", title: "视频" },
  { Choice: ".ql-link", title: "添加链接" },
  { Choice: ".ql-formula", title: "插入公式" },
  { Choice: ".ql-clean", title: "清除字体格式" },
  { Choice: '.ql-script[value="sub"]', title: "下标" },
  { Choice: '.ql-script[value="super"]', title: "上标" },
  { Choice: '.ql-indent[value="-1"]', title: "向左缩进" },
  { Choice: '.ql-indent[value="+1"]', title: "向右缩进" },
  { Choice: ".ql-header .ql-picker-label", title: "标题大小" },
  { Choice: '.ql-header .ql-picker-item[data-value="1"]', title: "标题一" },
  { Choice: '.ql-header .ql-picker-item[data-value="2"]', title: "标题二" },
  { Choice: '.ql-header .ql-picker-item[data-value="3"]', title: "标题三" },
  { Choice: '.ql-header .ql-picker-item[data-value="4"]', title: "标题四" },
  { Choice: '.ql-header .ql-picker-item[data-value="5"]', title: "标题五" },
  { Choice: '.ql-header .ql-picker-item[data-value="6"]', title: "标题六" },
  { Choice: ".ql-header .ql-picker-item:last-child", title: "标准" },
  { Choice: '.ql-size .ql-picker-item[data-value="small"]', title: "小号" },
  { Choice: '.ql-size .ql-picker-item[data-value="large"]', title: "大号" },
  { Choice: '.ql-size .ql-picker-item[data-value="huge"]', title: "超大号" },
  { Choice: ".ql-size .ql-picker-item:nth-child(2)", title: "标准" },
  { Choice: ".ql-align .ql-picker-item:first-child", title: "居左对齐" },
  {
    Choice: '.ql-align .ql-picker-item[data-value="center"]',
    title: "居中对齐",
  },
  {
    Choice: '.ql-align .ql-picker-item[data-value="right"]',
    title: "居右对齐",
  },
  {
    Choice: '.ql-align .ql-picker-item[data-value="justify"]',
    title: "两端对齐",
  },
];
export default {
  components: {
    quillEditor,
  },
  data() {
    return {
      // 使对话框的keyVal值发生变化从而让模板重新编译，使图片即使显示
      keyVal: 0,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 对话框标题
      title: undefined,
      // 对话框的左边距
      formLabelWidth: "120px",
      // 对话框是否显示
      open: false,
      // 封装图片的ip
      url: global.baseUrl,
      // 存放新闻资讯
      tableData: [],
      // 选中数组(存放选中的资讯id)
      ids: [],
      // 选中数组(存放选中的资讯标题)
      titles: [],
      // 查询表单
      queryParams: {
        pageNum: 1,
        pageSize: 5,
        title: undefined,
        editor: undefined,
      },
      // 对话框表单
      form: {},
      // 表单校验
      rules: {
        title: [{ required: true, message: "请输入资讯标题", trigger: "blur" }],
        editor: [{ required: true, message: "请输入作者", trigger: "blur" }],
        content: [{ required: true, message: "请输入内容", trigger: "blur" }],
        reviewer: [
          { required: true, message: "请输入审核人", trigger: "change" },
        ],
      },
      // 富文本编辑器配置
      editorOption: {
        modules: {
          toolbar: {
            container: [
              ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线
              ["blockquote", "code-block"], // 引用  代码块
              [{ header: 1 }, { header: 2 }], // 1、2 级标题
              [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表
              [{ script: "sub" }, { script: "super" }], // 上标/下标
              [{ indent: "-1" }, { indent: "+1" }], // 缩进
              [{ direction: "rtl" }], // 文本方向
              [
                {
                  size: [
                    "12",
                    "14",
                    "16",
                    "18",
                    "20",
                    "22",
                    "24",
                    "28",
                    "32",
                    "36",
                  ],
                },
              ], // 字体大小
              [{ header: [1, 2, 3, 4, 5, 6] }], // 标题
              [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
              // [{ font: ['songti'] }], // 字体种类
              [{ align: [] }], // 对齐方式
              ["clean"], // 清除文本格式
              ["image", "video"], // 链接、图片、视频
            ],
            handlers: {
              image: function (value) {
                if (value) {
                  // value === true
                  document.querySelector(".avatar-uploader input").click();
                } else {
                  this.quill.format("image", false);
                }
              },
            },
          },
          // 调整图片大小
          imageDrop: true,
          imageResize: {
            displayStyles: {
              backgroundColor: "black",
              border: "none",
              color: "white",
            },
            modules: ["Resize", "DisplaySize", "Toolbar"],
          },
        },
        placeholder: "请输入正文",
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 查询【支部资讯】列表
    getList() {
      getBranch(this.queryParams).then((res) => {
        this.tableData = res.rows;
        for (let i = 0; i < this.tableData.length; i++) {
          this.tableData[i].content = Base64.decode(this.tableData[i].content);
        }
        this.total = res.total;
      });
    },
    // 上传图片时接收到file对象并调用添加图片的接口
    upload(f) {
      // 1. 获取表单数据   formData 表单数据
      let formData = new FormData();
      formData.append("file", f.file);
      // 2. 发起请求
      addFile(formData).then((res) => {
        // 3. 请求成功之后  图片回显
        this.form.imgId = res.data.imgId;
        this.form.bucketName = res.data.bucketName;
        this.form.fileName = res.data.fileName;
        // 将对话框中的key的值+1，使模板重新编译从而使图片显示出来
        this.keyVal++;
      });
    },
    //上传前校验图片规则
    ImgBeforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG 和 Png 格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
        return false;
      }
    },
    // 重置表单
    reset() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 5,
        title: undefined,
        editor: undefined,
      };
    },
    resetForm() {
      this.form = {
        title: undefined,
        content: undefined,
        editor: undefined,
        reviewer: undefined,
        remark: undefined,
      };
    },
    // 搜索按钮
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置按钮
    handleRefresh() {
      this.reset();
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.titles = selection.map((item) => item.title);
      this.multiple = !selection.length;
    },
    // 新增按钮
    handleAdd() {
      this.resetForm();
      this.open = true;
      this.title = "添加资讯";
    },
    // 修改按钮
    marketUpdate(row) {
      this.resetForm();
      this.open = true;
      this.form = row;
      this.title = "修改资讯信息";
    },
    // 删除按钮
    handleDelete(row) {
      const roleIds = row.id || this.ids;
      const roleTitles = row.title || this.titles;
      this.$modal
        .confirm('是否确认删除标题为"' + roleTitles + '"的数据项？')
        .then(function () {
          return delBranch(roleIds);
        })
        .then(() => {
          this.getList();
        });
    },
    // 关闭对话框
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          this.getList();
          done();
        })
        .catch((_) => {});
    },
    // 取消对话框
    cancel() {
      this.open = false;
      this.getList();
    },
    /* 提交(确定)按钮 */
    submitForm() {
      this.form.content = Base64.encode(this.form.content);
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            updateBranch(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.getList();
              this.open = false;
            });
          } else {
            addBranch(this.form).then((res) => {
              this.$modal.msgSuccess("新增成功");
              this.getList();
              this.open = false;
            });
          }
        }
      });
    },

    // 富文本
    // 失去焦点事件
    onEditorBlur(quill) {},
    // 获得焦点事件
    onEditorFocus(quill) {},
    // 准备富文本编辑器
    onEditorReady(quill) {
      for (let item of titleConfig) {
        let tip = document.querySelector(".quill-editor " + item.Choice);
        if (!tip) continue;
        tip.setAttribute("title", item.title);
      }
    },
    // 内容改变事件
    onEditorChange({ quill, html, text }) {
      this.content = html;
    },
    // 富文本上传图片
    async onUploadHandler(f) {
      // 获取光标所在位置
      let quill = this.$refs.myQuillEditor.quill;
      let length = quill.getSelection().index;
      // 插入图片
      // 1. 获取表单数据   formData 表单数据
      let formData = new FormData();
      formData.append("file", f.file);
      // 2. 发起请求
      addFile(formData).then((res) => {
        // 3. 请求成功之后  图片回显
        this.imageUrl =
          this.url + res.data.bucketName + "/" + res.data.fileName;
        // 插入图片
        quill.insertEmbed(length, "image", this.imageUrl);
      });
      // 调整光标到最后
      quill.setSelection(length + 1);
    },
    //上传前校验图片规则
    ImgBeforeAvatarUpload1(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG 和 Png 格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
        return false;
      }
    },
  },
};
</script>

<style scoped>
.main {
  margin: 20px;
}
.omit {
  font-size: 14px;
  text-overflow: -o-ellipsis-lastline;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
}
.content {
  -webkit-line-clamp: 4;
}
.title {
  -webkit-line-clamp: 1;
}
.remark {
  -webkit-line-clamp: 2;
}
</style>